package app.goods.info.views;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import app.goods.info.constants.ConstontValue;
import app.goods.info.constants.GlobalCache;
import app.goods.info.services.CentralizedProcurementGoodsServie;
import app.goods.info.services.domain.CataLogue;
import app.goods.info.services.domain.CatalogueGoodsNames;
import app.goods.info.services.domain.GoodsInfo;
import app.goods.info.services.domain.ShopInfo;
import app.goods.info.utils.FileReaderUtils;
import app.goods.info.utils.InterfaceUtils;
import app.goods.info.utils.PropertiesUtils;
import app.goods.info.views.listeners.QuantityCellEditorListener;
import app.goods.info.views.listeners.RefreshActionPerformListenner;
import app.goods.info.views.models.CatalogueGoodsNamesTableModle;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

public class MainFrame {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					GlobalCache.getInstance().initAllCache();
					MainFrame window = new MainFrame();
					InterfaceUtils.alignCenter(window.frame);
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public void show() {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					MainFrame window = new MainFrame();
					window.frame.setLocationRelativeTo(null);
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainFrame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setAlwaysOnTop(false);
		frame.setBounds(100, 100, 1300, 800);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JLabel statusLable = new JLabel("");
		JPanel panel = new JPanel();
		frame.getContentPane().add(panel, BorderLayout.NORTH);

		JButton startDownloadDataButton = new JButton("开始下载");

		startDownloadDataButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				startDownloadDataButton.setEnabled(false);

				long now = System.currentTimeMillis();
				CentralizedProcurementGoodsServie centralizedProcurementGoodsServie = new CentralizedProcurementGoodsServie();
				statusLable.setText("正在下载数据...");
				new Thread(() -> {
					List<GoodsInfo> allGoods = centralizedProcurementGoodsServie.getAllCentralizedGoods();
					long end = System.currentTimeMillis();
					SwingUtilities.invokeLater(() -> {
						String text = "下载完成，下载数据：" + allGoods.size() + "条记录，共耗时："
								+ ((System.currentTimeMillis() - now) / 1000) + "秒";
						List<String> errorCatalogueList = new ArrayList<String>();
						GlobalCache.getInstance().getErrorCataLogue().forEach(cataLogue -> {
							errorCatalogueList.add(cataLogue.getCatalogueName());
						});
						statusLable.setText(text + JSONUtil.toJsonPrettyStr(errorCatalogueList) + "下载失败");
						startDownloadDataButton.setEnabled(true);
						buildTabbedPanel(true);
						InterfaceUtils.cacaulateTotalPrice(frame);
					});
				}).start();
			}
		});
		panel.add(startDownloadDataButton);
		JButton resetGoodsNumberButton = new JButton("重置商品数量");
		resetGoodsNumberButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				InterfaceUtils.resetAllCataLogueGoodsNumbers(frame);

			}
		});
		panel.add(resetGoodsNumberButton);

		JButton setShop = new JButton("设置");
		panel.add(setShop);
		setShop.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				AllShopSettingFrame allShopSettingFrame = new AllShopSettingFrame(frame);
				allShopSettingFrame.setVisible(true);

			}
		});

		JComboBox<Integer> waitTimeCheckBox = new JComboBox<Integer>();
		for (int i = 0; i < 10; i++) {
			waitTimeCheckBox.addItem((i + 1) * 100);
		}
		Integer waitTimeConf = Integer
				.valueOf(PropertiesUtils.getValueByKeyFromResources(ConstontValue.CONFIG_FILE_NAME, "waitTime"));
		waitTimeCheckBox.setSelectedItem(waitTimeConf);
		waitTimeCheckBox.addItemListener(itemListener -> {
			if (itemListener.getStateChange() == ItemEvent.SELECTED) {
				// 当选项被选中时执行的操作
				Integer selectedItem = (Integer) itemListener.getItem();
				PropertiesUtils.setValueForKey(ConstontValue.CONFIG_FILE_NAME, "waitTime",
						String.valueOf(selectedItem));
			}
		});
		panel.add(waitTimeCheckBox);

		JPanel statusPanel = new JPanel();
		statusPanel.add(statusLable);
		JPanel leftShopNameJPanel = buildTargetShopTablePanel();
		frame.getContentPane().add(leftShopNameJPanel, BorderLayout.WEST);
		frame.getContentPane().add(statusPanel, BorderLayout.SOUTH);
		JTabbedPane tabbedPane = buildTabbedPanel(false);
		frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
	}

	private JTabbedPane buildTabbedPanel(boolean downloadFromServer) {
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		for (Iterator<CataLogue> iterator = GlobalCache.getInstance().getTargetCataLogues().iterator(); iterator
				.hasNext();) {
			CataLogue cataLogue = iterator.next();
			JPanel catalogueGoodsPanel = buildeCatalogueGoodsPanel(cataLogue, downloadFromServer);
			tabbedPane.addTab(cataLogue.getCatalogueName(), catalogueGoodsPanel);
		}
		return tabbedPane;
	}

	/**
	 * 构建每个品类的tab标签面板
	 * 
	 * @param catalogue
	 * @param goodsList
	 * @return
	 */
	private JPanel buildeCatalogueGoodsPanel(CataLogue catalogue, boolean downloadFromServer) {
		JPanel contentJPanel = new JPanel();
		contentJPanel.setLayout(new BorderLayout());
		JPanel refreshPanel = new JPanel();
		refreshPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		JButton refeshButton = new JButton("刷新");
		refeshButton.addActionListener(new RefreshActionPerformListenner(catalogue, frame));
		refreshPanel.add(refeshButton);
		JLabel refreshStatus = new JLabel("");
		refreshStatus.setName("refresh-status-".concat(catalogue.getCatalogueName()));
		refreshPanel.add(refreshStatus);
		contentJPanel.add(refreshPanel, BorderLayout.NORTH);

		JPanel catalogueGoodsPanel = new JPanel();
		catalogueGoodsPanel.setLayout(new BoxLayout(catalogueGoodsPanel, BoxLayout.X_AXIS));
		JPanel leftPanel = new JPanel();
		leftPanel.setName(catalogue.getCatalogueName());
		catalogueGoodsPanel.add(leftPanel);
		leftPanel.setLayout(new BorderLayout(0, 0));

		JPanel panel_2 = new JPanel();
		leftPanel.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.Y_AXIS));

		JPanel leftUpPanel = new JPanel();
		panel_2.add(leftUpPanel);
		leftUpPanel.setLayout(new BorderLayout(0, 0));
		leftUpPanel.setPreferredSize(new Dimension(150, frame.getHeight()));

		JTable catalogueGoodsNamesTable = buildCatalogueGoodsNamesTable(catalogue);
		JScrollPane scrollPane = new JScrollPane(catalogueGoodsNamesTable);

		leftUpPanel.add(scrollPane, BorderLayout.CENTER);

		JPanel rightPanel = new JPanel();
		catalogueGoodsPanel.add(rightPanel);
		rightPanel.setLayout(new BorderLayout(0, 0));

		JTable catalogueGoodsInfoTable = buildCatalogueGoodsTable(catalogue, downloadFromServer);
		JScrollPane catalogueGoodsInfoJScrollPane = new JScrollPane(catalogueGoodsInfoTable);
		rightPanel.add(catalogueGoodsInfoJScrollPane, BorderLayout.CENTER);
		catalogueGoodsPanel.setName("tab-name-" + catalogue.getCatalogueName());

		contentJPanel.add(catalogueGoodsPanel, BorderLayout.CENTER);
		return contentJPanel;
	}

	/**
	 * 根据品类信息，创建这个品类下所有的商品名称表格 <br>
	 * 
	 * @param catalogue 品类信息
	 * @return
	 */
	private JTable buildCatalogueGoodsNamesTable(CataLogue catalogue) {
		List<String> columnNames = new ArrayList<String>();
		columnNames.add("序号");
		columnNames.add("商品名称");
		columnNames.add("商品数量");
		Object[][] dataRows = new Object[0][0];
		for (int i = 0; i < GlobalCache.getInstance().getTargetGoodsNames().size(); i++) {
			CatalogueGoodsNames catalogueGoodsName = GlobalCache.getInstance().getTargetGoodsNames().get(i);
			if (catalogue.getCatalogueName().equals(catalogueGoodsName.getCatalogueName())) {
				dataRows = new Object[catalogueGoodsName.getGoodsNames().size()][3];
				for (int ii = 0; ii < catalogueGoodsName.getGoodsNames().size(); ii++) {
					dataRows[ii][0] = ii;
					dataRows[ii][1] = catalogueGoodsName.getGoodsNames().get(ii);
					dataRows[ii][2] = "0";
				}
			}
		}
		;

		DefaultTableModel model = new CatalogueGoodsNamesTableModle(dataRows, columnNames.toArray());

		// 创建 JTable 实例，并设置模型
		JTable table = new JTable(model);
		table.getColumnModel().getColumn(0).setPreferredWidth(10);
		table.getColumnModel().getColumn(1).setPreferredWidth(130);
		table.getColumnModel().getColumn(2).setPreferredWidth(10);
		// 设置商品数量列可编辑，并添加编辑后的事件处理
		DefaultCellEditor singleclick = new DefaultCellEditor(new JTextField());
		singleclick.setClickCountToStart(1);
		singleclick.addCellEditorListener(new QuantityCellEditorListener(frame));
		table.getColumnModel().getColumn(2).setCellEditor(singleclick);

		// 5设置单元格不可拖动
		table.getTableHeader().setReorderingAllowed(false);
		// 6设置不可改变列宽
		table.getTableHeader().setResizingAllowed(false);

		table.setCellSelectionEnabled(true);
		table.setName("table-name-list-".concat(catalogue.getCatalogueName()));
		return table;
	}

	/**
	 * 所有商家名称表格 <br>
	 * 
	 * @return
	 */
	private JPanel buildTargetShopTablePanel() {

		JPanel leftShopNamePanel = new JPanel();
		leftShopNamePanel.setLayout(new BorderLayout(0, 0));
		List<String> columnNames = new ArrayList<String>();
		columnNames.add("商家名称");
		columnNames.add("总价");
		List<ShopInfo> targetShopInfos = GlobalCache.getInstance().getAllShopInfos().stream()
				.filter(shopInfo -> shopInfo.getStatus().equals("ON")).collect(Collectors.toList());

		Object[][] dataRows = new Object[targetShopInfos.size()][2];
		for (int i = 0; i < targetShopInfos.size(); i++) {
			ShopInfo shopInfo = targetShopInfos.get(i);
			dataRows[i][0] = shopInfo.getShopName();
			dataRows[i][1] = "0.00";
		}
		;

		DefaultTableModel model = new CatalogueGoodsNamesTableModle(dataRows, columnNames.toArray());

		// 创建 JTable 实例，并设置模型
		JTable shopNameTable = new JTable(model);
		// 5设置单元格不可拖动
		shopNameTable.getTableHeader().setReorderingAllowed(false);
		shopNameTable.setName("table-shop-list");

		// 使用 TableRowSorter 进行排序
		TableRowSorter<TableModel> sorter = new TableRowSorter<>(model);
		shopNameTable.setRowSorter(sorter);

		// 对第二列进行降序排序
		sorter.setSortable(0, false);
		sorter.setSortable(1, true);
		sorter.setSortsOnUpdates(true);
		sorter.setComparator(1, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				return Double.valueOf(o2).compareTo(Double.valueOf(o1));
			}
		});
		List<SortKey> sortKeys = new ArrayList<>();
		sortKeys.add(new SortKey(1, SortOrder.DESCENDING));
		sorter.setSortKeys(sortKeys);
		JScrollPane scrollPaneShopNameTable = new JScrollPane(shopNameTable);
		scrollPaneShopNameTable.setName("scrollPaneShopNameTable");
		scrollPaneShopNameTable.setRowHeaderView(new RowHeader(shopNameTable, 30));
		leftShopNamePanel.add(scrollPaneShopNameTable, BorderLayout.CENTER);
		leftShopNamePanel.setPreferredSize(new Dimension(300, frame.getHeight()));
		shopNameTable.getColumnModel().getColumn(0).setPreferredWidth(190);
		shopNameTable.getColumnModel().getColumn(1).setPreferredWidth(60);

		// 5设置单元格不可拖动
		shopNameTable.getTableHeader().setReorderingAllowed(false);
		// 6设置不可改变列宽
		shopNameTable.getTableHeader().setResizingAllowed(false);
		shopNameTable.setCellSelectionEnabled(true);
		shopNameTable.setEnabled(false);
		shopNameTable.setDefaultRenderer(Object.class, new ColroTableCellRenderer(frame));
		return leftShopNamePanel;
	}

	/**
	 * 所有商家名称表格 <br>
	 * 
	 * @return
	 */
	private JTable buildCatalogueGoodsTable(CataLogue cataLogue, boolean downloadFromServer) {
		List<String> columnNames = new ArrayList<String>();
		columnNames.add("序号");
		columnNames.add("供应商名称");
		columnNames.add("商品名称");
		columnNames.add("单位");
		columnNames.add("价格");
		columnNames.add("数量");
		List<GoodsInfo> goodsInfos = new ArrayList<GoodsInfo>();
		if (downloadFromServer) {
			goodsInfos = GlobalCache.getInstance().getCatalogueGoodsInfos().get(cataLogue.getCatalogueName());
		} else {
			// 加载缓存的上次下载的数据
			goodsInfos = new ArrayList<GoodsInfo>();
			String jsonString = FileReaderUtils.readFileQuikly("data/" + cataLogue.getCatalogueNo() + ".json");
			JSONArray allGoods = JSONUtil.parseArray(jsonString);
			goodsInfos = JSONUtil.toList(allGoods, GoodsInfo.class);
			GlobalCache.getInstance().getCatalogueGoodsInfos().put(cataLogue.getCatalogueName(), goodsInfos);
		}
		List<GoodsInfo> slefGoods = new ArrayList<GoodsInfo>();
		Iterator<GoodsInfo> iterator = goodsInfos.iterator();
		while (iterator.hasNext()) {
			GoodsInfo element = iterator.next();
			if (element.getShopName().equals(ConstontValue.SELF_SHOP)) {
				iterator.remove();
				slefGoods.add(element);
			}
		}
		goodsInfos.addAll(0, slefGoods);

		Object[][] dataRows = new Object[goodsInfos.size()][6];
		for (int i = 0; i < goodsInfos.size(); i++) {
			GoodsInfo goodsInfo = goodsInfos.get(i);
			dataRows[i][0] = i;
			dataRows[i][1] = goodsInfo.getShopName();

			if ("正大翅中".equals(goodsInfo.getGoodsName()) || "正大翅根".equals(goodsInfo.getGoodsName())
					|| "益客翅根".equals(goodsInfo.getGoodsName())) {
				dataRows[i][2] = goodsInfo.getGoodsName() + "（" + goodsInfo.getGoodsUnit() + "）";
			} else if ("益客翅中".equals(goodsInfo.getGoodsName())) {
				dataRows[i][2] = "益客翅中（M号）240-260/箱";
			} else {
				dataRows[i][2] = goodsInfo.getGoodsName();
			}

			dataRows[i][3] = goodsInfo.getGoodsUnit();
			dataRows[i][4] = goodsInfo.getGoodsPrice();
			dataRows[i][5] = "0";
		}
		;

		DefaultTableModel model = new CatalogueGoodsNamesTableModle(dataRows, columnNames.toArray());

		// 创建 JTable 实例，并设置模型
		JTable table = new JTable(model);
		// 5设置单元格不可拖动
		table.getTableHeader().setReorderingAllowed(false);
		table.getColumnModel().getColumn(0).setPreferredWidth(20);
		table.getColumnModel().getColumn(1).setPreferredWidth(150);
		table.getColumnModel().getColumn(2).setPreferredWidth(150);
		table.getColumnModel().getColumn(3).setPreferredWidth(30);
		table.getColumnModel().getColumn(4).setPreferredWidth(40);
		table.getColumnModel().getColumn(5).setPreferredWidth(30);

		// 设置商品数量列可编辑，并添加编辑后的事件处理
		DefaultCellEditor singleclick = new DefaultCellEditor(new JTextField());
		singleclick.setClickCountToStart(1);
		singleclick.addCellEditorListener(new QuantityCellEditorListener(frame));
		table.getColumnModel().getColumn(4).setCellEditor(singleclick);

		// 使用 TableRowSorter 进行排序
		TableRowSorter<TableModel> sorter = new TableRowSorter<>(model);
		table.setRowSorter(sorter);

		// 对第二列进行降序排序
		sorter.setSortable(2, true);
		sorter.setSortable(4, true);
		sorter.setSortable(5, true);
		sorter.setSortsOnUpdates(true);
		table.setName("table-goods-list-".concat(cataLogue.getCatalogueName()));
		return table;
	}
}